package com.baaio.xml;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * 该类用来查找配置文件里的数据
 * 
 * @author baaio QQ:398673054
 * 
 */
public class XMLGetData
{

	/**
	 * 获得配置文件里名字为item的标签的value
	 * 
	 * @param path
	 *            配置文件所在路径
	 * @param item
	 * @return List
	 */
	private static List<String> xmlGetData(String path, String item)
	{

		try
		{
			File f = new File(path);
			FileInputStream is;
			is = new FileInputStream(f);
			List<String> list = new ArrayList<String>();
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();

			Document document = builder.parse(is);
			Element element = document.getDocumentElement();
			NodeList StringNodes = null;
			if (item.equals("*"))
			{
				StringNodes = element.getElementsByTagNameNS("*", "*");
			}
			else
			{
				StringNodes = element.getElementsByTagName(item);
			}
			Element StringElement = null;
			String st = null;
			for (int i = 0; i < StringNodes.getLength(); i++)
			{
				StringElement = (Element) StringNodes.item(i);
				st = StringElement.getFirstChild().getNodeValue();
				// System.out.println("ST:" + i + ":" + st);
				list.add(st);
				st = "";
			}// end for i

			return list;
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	public static List<String> getRoot(String path, String item)
	{

		return xmlGetData(path, item);
	}

}
